# 用户登录
from rest_framework.views import APIView
from utils.result import R
from utils.status_code import StatusCodeEnum 
from utils.aliverify_code import * 
from api.models import ItEduUser,ItEduUserInfo,ItEduCommentLesson
import hashlib

class LoginAPIView(APIView):
    
    def get(self,request):
        """判断是否登录

        Args:
            request (_type_): _description_
        """
        user_pk = request.session.get("user_pk",None)

        if user_pk:
            return R.ok().to_json_response()
        return R.other_result(StatusCodeEnum.NO_LOGIN_ERR).to_json_response()
    
    def put(self,request):
        """发送验证码

        Args:
            request (_type_): _description_
        """
        verify_code = create_6_verify_code()
        request.session["verify_code"] = verify_code

        phone_num = request.data.get("phone_num")
        request.session["phone_num"] = phone_num
        
        res = send_sms_code(phone_num,verify_code)

        if res:
            return R.ok().to_json_response()
        else:
            return R.other_result(StatusCodeEnum.VERIFY_CODE_ERROR).to_json_response()

    def post(self,request):
        """实现登录

        Args:
            request (_type_): _description_
        """
        verify_code = request.data.get("verify_code")
        real_verify_code = request.session.get("verify_code")

        phone_num = request.data.get("phone_num")
        real_phone_num = request.session.get("phone_num")

        if verify_code == real_verify_code and phone_num == real_phone_num:
            del request.session['verify_code']
            del request.session['phone_num']

            phone_sha256 = hashlib.pbkdf2_hmac("sha256", phone_num.encode("utf-8"), "itedu".encode("utf-8"), 600000).hex()[0]
            
            user = ItEduUser.objects.filter(phone_sha256=phone_sha256).first()
            
            # 如果用户不存在就创建
            if not user:
                nickname = ""
                user_info = ItEduUserInfo.objects.create()
                user = ItEduUser.objects.create(user_info=user_info,nickname=nickname,phone_sha256=phone_sha256,vip_type="普通会员")

            request.session["user_pk"] = user._id

            # 返回用户信息
            user = {
                "nickname":user.nickname,
                "avatar_image":user.avatar_image,
                "intro":user.intro,
                "vip_type":user.vip_type,
                "score":user.score,
                "user_info":{
                    "tags":user.user_info.tags,
                    "credit":user.user_info.credit,
                    "comment_num":ItEduCommentLesson.objects.filter(user=user).count()
                }
            }
            return R().data_result(user=user)
        else:
            return R.login_error() 
        
    
    def delete(self,request):
        """退出

        Args:
            request (_type_): _description_
        """
        
        del request.session["user_pk"]
        
        return R.ok().to_json_response()